package com.jrtc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jrtc.base.config.constants.PublicConstants;
import com.jrtc.base.entity.bo.*;
import com.jrtc.base.entity.vo.ArticulusReportVo;
import com.jrtc.base.entity.vo.IdNameInfoVo;
import com.jrtc.dao.*;
import com.jrtc.service.ArticulusReportService;
import com.jrtc.service.CaseService;
import com.jrtc.service.DoctorService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service("caseService")
public class CaseServiceImpl implements CaseService
{
    @Resource
    private CaseDao caseDao;
    @Resource
    private DoctorService doctorService;
    @Resource
    private HospitalDao hospitalDao;

    /**
     * 病例列表
     * */
    @Override
    public IPage<Case> caseList(Long pageNo, Long pageSize, HttpServletRequest request) throws Exception {
        Doctor loginDoctor;
        try {
            loginDoctor = doctorService.getLoginDoctor(request);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        if (loginDoctor == null){
            throw new Exception("登录已过期");
        }
        Page<Case> page = new Page<>(pageNo, pageSize);
        IPage<Case> caseList = caseDao.caseList(page, loginDoctor.getDoctorId());
        if (caseList != null && caseList.getRecords().size() > 0){
            for (Case aCase : caseList.getRecords()) {
                aCase.setDoctorName(loginDoctor.getDoctorName());

                Hospital hospital = hospitalDao.hospitalByNum(loginDoctor.getHospitalCode());
                if (hospital != null){
                    aCase.setName(hospital.getHospitalName());
                }
            }
        }
        return caseList;
    }

    /**
     * 新增病例
     * */
    @Override
    public int insertCase(Case c, HttpServletRequest request) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Doctor loginDoctor;
        try {
            loginDoctor = doctorService.getLoginDoctor(request);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        if (loginDoctor == null){
            throw new Exception("登录已过期");
        }
        c.setDoctorId(loginDoctor.getDoctorId());
        c.setHospitalCode(loginDoctor.getHospitalCode());
        c.setDateTime(format.parse(format.format(new Date())));

        int i;
        if (c.getId() != null && c.getId() != 0){
            i = caseDao.updateCase(c);
        }
        else {
            i = caseDao.insertCase(c);
        }
        return i;
    }
}